import React, { useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';

interface LayoutProps {
  children: React.ReactNode;
  title?: string;
}

const Layout: React.FC<LayoutProps> = ({ children, title = '学途 - 继续教育学习平台' }) => {
  const navigate = useNavigate();
  const {
    isLoggedIn,
    loading,
    showUserMenu,
    setShowUserMenu,
    handleLogout,
    getUserDisplayName,
    getUserAvatarLetter,
    getUserAvatar
  } = useAuth();

  useEffect(() => {
    const originalTitle = document.title;
    document.title = title;
    return () => { document.title = originalTitle; };
  }, [title]);

  // 全局搜索处理
  const handleGlobalSearchKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      const searchTerm = (e.target as HTMLInputElement).value.trim();
      if (searchTerm) {
        navigate(`/course-list?search=${encodeURIComponent(searchTerm)}`);
      }
    }
  };

  // 点击外部关闭用户菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (showUserMenu) {
        const target = event.target as Element;
        if (!target.closest('.user-menu-container')) {
          setShowUserMenu(false);
        }
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [showUserMenu, setShowUserMenu]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        <span className="ml-3 text-gray-600">加载中...</span>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 顶部导航栏 */}
      <header className="bg-white shadow-sm border-b border-gray-200 fixed top-0 left-0 right-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            {/* Logo和网站名称 */}
            <div className="flex items-center space-x-3">
              <div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
                <i className="fas fa-graduation-cap text-white text-lg"></i>
              </div>
              <span className="text-xl font-bold text-gray-900">学途</span>
            </div>
            
            {/* 主导航菜单 */}
            <nav className="hidden md:flex items-center space-x-8">
              <Link to="/home" className="text-gray-600 hover:text-blue-600 py-1 transition-colors">
                首页
              </Link>
              <Link to="/course-list" className="text-gray-600 hover:text-blue-600 py-1 transition-colors">
                课程中心
              </Link>
              <Link to="/about-us" className="text-gray-600 hover:text-blue-600 py-1 transition-colors">
                关于我们
              </Link>
              <Link to="/help-center" className="text-gray-600 hover:text-blue-600 py-1 transition-colors">
                帮助中心
              </Link>
            </nav>
            
            {/* 搜索框 */}
            <div className="hidden lg:flex items-center">
              <div className="relative">
                <input 
                  type="text" 
                  placeholder="搜索课程、讲师..." 
                  className="w-64 pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  onKeyPress={handleGlobalSearchKeyPress}
                />
                <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
              </div>
            </div>
            
            {/* 用户菜单 */}
            <div className="flex items-center space-x-4">
              {isLoggedIn && (
                <button className="relative p-2 text-gray-600 hover:text-blue-600 transition-colors">
                  <i className="fas fa-bell text-lg"></i>
                  <span className="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full"></span>
                </button>
              )}
              
              {isLoggedIn ? (
                /* 已登录状态 */
                <div className="relative user-menu-container">
                  <button 
                    onClick={() => setShowUserMenu(!showUserMenu)}
                    className="flex items-center space-x-2 px-3 py-2 text-gray-600 hover:text-blue-600 transition-colors"
                  >
                    {getUserAvatar() ? (
                      <img 
                        src={getUserAvatar()}
                        alt="用户头像" 
                        className="w-8 h-8 rounded-full object-cover"
                      />
                    ) : (
                      <div className="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center text-white text-sm">
                        {getUserAvatarLetter()}
                      </div>
                    )}
                    <span className="hidden md:block">
                      {getUserDisplayName()}
                    </span>
                    <i className="fas fa-chevron-down text-xs"></i>
                  </button>
                  
                  {showUserMenu && (
                    <div className="absolute right-0 top-full mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-2 z-50">
                      <Link 
                        to="/personal-center" 
                        className="block px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 transition-colors"
                        onClick={() => setShowUserMenu(false)}
                      >
                        <i className="fas fa-user mr-2"></i>
                        个人中心
                      </Link>
                      <Link 
                        to="/enrolled-courses" 
                        className="block px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 transition-colors"
                        onClick={() => setShowUserMenu(false)}
                      >
                        <i className="fas fa-book mr-2"></i>
                        我的课程
                      </Link>
                      <Link 
                        to="/messages" 
                        className="block px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 transition-colors"
                        onClick={() => setShowUserMenu(false)}
                      >
                        <i className="fas fa-envelope mr-2"></i>
                        站内信
                      </Link>
                      <Link 
                        to="/account-security" 
                        className="block px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 transition-colors"
                        onClick={() => setShowUserMenu(false)}
                      >
                        <i className="fas fa-shield-alt mr-2"></i>
                        账户安全
                      </Link>
                      <hr className="my-2" />
                      <button 
                        onClick={handleLogout}
                        className="block w-full text-left px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-red-600 transition-colors"
                      >
                        <i className="fas fa-sign-out-alt mr-2"></i>
                        退出登录
                      </button>
                    </div>
                  )}
                </div>
              ) : (
                /* 未登录状态 */
                <div className="flex items-center space-x-3">
                  <Link to="/login" className="px-4 py-2 text-gray-600 hover:text-blue-600 transition-colors">
                    登录
                  </Link>
                  <Link to="/register" className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                    注册
                  </Link>
                </div>
              )}
            </div>
          </div>
        </div>
      </header>

      {/* 主内容区域 */}
      <main className="pt-16">
        {children}
      </main>
    </div>
  );
};

export default Layout;